package com.codingfly.controller;

import com.codingfly.controller.common.BaseController;
import com.codingfly.core.exception.BizException;
import com.codingfly.core.util.AssertUtils;
import com.codingfly.entity.SysDict;
import com.codingfly.entity.SysDictItem;
import com.codingfly.model.Result;
import com.codingfly.model.dto.DictDto;
import com.codingfly.model.dto.DictItemDto;
import com.codingfly.model.vo.DictItemVo;
import com.codingfly.service.SysDictItemService;
import com.codingfly.service.SysDictService;
import com.codingfly.service.impl.CommonServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/dictItem")
public class DictItemController extends BaseController {
    @Autowired
    private SysDictService sysDictService;
    @Autowired
    private SysDictItemService sysDictItemService;
    @Autowired
    private CommonServiceImpl commonServiceImpl;

    @PostMapping
    public Result add(@RequestBody DictItemDto dto) {
        checkParams(dto, "code", "name", "dictId", "auditTime");
        AssertUtils.isTrue(sysDictService.findById(dto.getDictId())!=null, "该分类不存在或者已删除");
        SysDictItem parentItem = null;
        if (!ObjectUtils.isEmpty(dto.getParentId())) {
            parentItem = Optional.ofNullable(sysDictItemService.findById(dto.getParentId())).orElseThrow(()->new BizException("父级不存在或者已删除"));
        }
        SysDictItem item = new SysDictItem();
        item.setDictId(dto.getDictId());
        item.setName(dto.getName());
        item.setCode(dto.getCode());
        item.setAuditTime(dto.getAuditTime());
        item.setDescription(dto.getDescription());
        if (parentItem!=null) {
            item.setParentId(parentItem.getId());
            item.setLevel(parentItem.getLevel()!=null? parentItem.getLevel()+1:1);
        } else {
            item.setLevel(1);
        }
        item.setOrderNo(commonServiceImpl.queryNextOrderNoLong("sys_dict_item"));
        sysDictItemService.save(item);
        if (parentItem!=null) {
            if (!StringUtils.isEmpty(parentItem.getFullPath())) {
                item.setFullPath(parentItem.getFullPath()+","+item.getId());
            }
        } else {
            item.setFullPath(item.getId()+"");
        }
        sysDictItemService.save(item);
        return Result.success(item.getId());
    }

    @PutMapping("/{id}")
    public Result add(@PathVariable("id") Long id, @RequestBody DictItemDto dto) {
        checkParams(dto, "code", "name", "auditTime");
        SysDictItem item = Optional.ofNullable(sysDictItemService.findById(id)).orElseThrow(()->new BizException("该节点不存在或者已删除"));
        if (!dto.getCode().equals(item.getCode())) {
            AssertUtils.isTrue(sysDictItemService.findByCode(dto.getCode())==null, "该CODE编码 "+dto.getCode()+" 已存在");
        }
        item.setName(dto.getName());
        item.setCode(dto.getCode());
        item.setAuditTime(dto.getAuditTime());
        item.setDescription(dto.getDescription());
        sysDictItemService.save(item);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable("id") Long id) {
        AssertUtils.isTrue(!sysDictItemService.hasChildren(id), "请先删除子节点");
        sysDictService.deleteById(id);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<SysDictItem> queryById(@PathVariable("id") Long id) {
        return Result.success(sysDictItemService.findById(id));
    }

    @GetMapping("/{id}/children")
    public Result<SysDictItem> children(@PathVariable("id") Long id) {
        return Result.success(sysDictItemService.children(id));
    }

    @PatchMapping("/move/{id}")
    public Result move(@PathVariable("id") Integer id, @RequestParam("action") String action) {
        if ("up".equals(action)) {
            commonServiceImpl.upOrderNoWithoutParent("sys_dict_item", id);
        } else if ("down".equals(action)) {
            commonServiceImpl.upOrderNoWithoutParent("sys_dict_item", id);
        }
        return Result.success();
    }

}
